by Ron Schwarz
In this chapter
This chapter describes VBScript language features. If you're familiar with Visual Basic, you can use this chapter, as well as Chapter 13, "Comparing VBScript, VBA, and Visual Basic," to apprise yourself of the differences you'll run into with VBScript. Many of the language elements named in this chapter are discussed in-depth in other chapters (references to these are provided) and are therefore given light coverage here.
If you're new to Visual Basic programming in general, this chapter will give you a good understanding of the language and capabilities of VB/VBS code. Other chapters in this book focus on structural aspects of scripting and event handling, specific language topics, visual program design using the ActiveX Control Pad and HTML Layout features, and other programming issues; this chapter covers the language and syntax as a whole, and points you to places in the book where specific features are discussed in-depth.
Language elements are covered in groups of topically related methods, statements functions, and keywords. This chapter is more of a guide than a reference; it presents each group of language features in the context of similar related features, and the groups are presented in order of typical frequency of use.
Each section contains a table listing related features (with a short description of each) and tutorial information describing the commonly used language elements in each category.
VBScript contains a variety of language elements pertaining to variable and procedure declarations, and array handling. Table 22.1 lists them.
Table 22.1 Declaration and Array Handling Elements
Keyword | Description |
Option Explicit | Requires all variables to be declared before they can be used |
Sub | Declaration keyword for Sub procedures |
Function | Declaration keyword for Function procedures |
Public | Declares a variable or array to be available to all procedures regardless of where it is declared |
Private | Declares a variable or array to be local to the script in which it is declared |
Dim | Declares a variable or array; scope is determined by placement of Dim statement |
ReDim | Resizes an array; can only be used with dynamic arrays |
Erase | Clears contents of an array |
IsArray | Reports whether a variable is or is not an array |
Lbound | Returns lowest element of an array (Always 0 in VBScript) |
Ubound | Returns highest element of an array |
See Chapter 15, "VBScript Data Types and Variables," for further discussion of arrays.
See Chapter 19, "VBScript Procedures," for in-depth coverage of declaration and procedure calling issues.
Unlike Visual Basic (which provides options for array base subscript, string comparison modes, and variable declaration scope), the only option implemented in VBScript is Option Explicit. When Option Explicit is selected, a variable must be declared before it can be used, or an error will occur. When Option Explicit is not used, a variable will be automatically created the first time it is referenced. (This does not apply to arrays, however; they must be explicitly dimensioned prior to use, regardless of Option Explicit settings.)
To use Option Explicit, simply place it as the first statement in your script, before any code or procedures.
While it may seem tempting to avoid using Option Explicit, it's recommended that you include it in anything beyond the simplest of scripts. The safety net it provides more than compensates for the slight inconvenience of having to explicitly declare each variable before use. Remember, VBScript doesn't have the sophisticated analysis and debugging tools that makes Visual Basic development so effortless; with VBScript you need every advantage you can get. Being able to flag bugs caused by simple typos in variable names can save you hours of grief in a single project, and Option Explicit provides that ability.
Sub and Function are used to declare Sub procedures and Functions. A Sub procedure is a block of code that is invoked by using its name (as if it were a built-in statement, or method) and following it with any parameters that are declared in the actual Sub.
To declare a Sub procedure, use this syntax:
Sub ProcedureName (Arg1, Arg2, Arg3, ...)
A procedure named ChangeURL, which accepted one argument named NewURL, would be declared as:
Sub ChangeURL (NewURL)
To invoke it and pass it a value of "www.microsoft.com", you'd use:
ChangeURL "www.microsoft.com"
A complete routine might look like Listing 22.1.
Listing 22.1 Example Sub Procedure Invocation
In the example in Listing 22.1, we first use Trim to remove any leading and trailing spaces from the NewURL variable. Then we test to see if it's got anything left in it. If the result is "" (an empty string), we exit the Sub procedure.
If the variable is greater than an empty string, we create a new .href for the Location object by combining the "HTTP://" prefix with the contents of NewURL.
The Sub procedure ends with an "End Sub" statement.
While you normally invoke a Sub procedure by typing its name and any required arguments (separated by commas), you may encounter an alternate syntax. The Call statement can be used, in this form:
Call AnySubProcedure (arg1, arg2, arg3)
The main difference here (apart from the actual inclusion of the Call keyword, of course) is the fact that the argument list must be surrounded by parentheses. When invoking a Sub procedure without the Call statement, you cannot use the parentheses. (The Call syntax is included for backward compatibility with versions of the BASIC language that predate the current procedure-name-only invocation style.)
Functions are declared in a similar manner as Sub procedures:
Function FunctionName (Arg1, Arg2, Arg3, ...)
Invoking a Function is a bit different, however; unlike a Sub procedure, a Function returns a value in its name. Here's a typical Function procedure:
Function BuildURL (NewURL)
BuildURL = "HTTP://" & NewUrl
End Function
In this example, we build a URL by passing an address to the function and returning "HTTP://" with the address concatenated. To return the value, we assign it to the function, just as if we were assigning it to a variable. We can combine the preceding two examples and use a Sub and Function procedure to modularize our code, as shown in Listing 22.2.
Listing 22.2 Using Sub and Function Procedures
The ChangeURL Sub procedure in Listing 22.2 calls BuildURL and passes the result to the Location.href property. The code is invoked exactly as in the prior ChangeURL example:
ChangeURL "www.microsoft.com"
Three keywords deal with variable declaration: Dim, Public, and Private. Once a variable is declared, the result is identical. The only difference is scope. (Scope determines in which context(s) a variable will exist.) When declared Public, a variable will be available in all procedures. When declared Private, it will be limited to the script in which it appears. When declared with Dim, scope is determined by context; if you Dim a variable at the script level (outside a procedure), it will be available to all procedures in that script. If you Dim it within a procedure, it will be local to that procedure.
Here's an example of the three forms of variable declaration:
The Public UserName variable will be available in all scripts, the Private Tally variable will only be available in the script in which it's used, and the ItemCount variable will only be available in the RefreshInfo procedure.
As this book goes to press, Public and Private keywords are documented but not yet implemented in the pre-release version of Internet Explorer that is available for testing.
Arrays are lists of variables. They are created with the same three declaration keywords as variables and are subject to the same scoping rules. Here is a typical array declaration:
Dim Age(10)
This creates an array named Age, with 11 elements (arrays begin with 0). To access a specific element of an array, use it as you would any other variable but include its subscript in parentheses; for example, Age(5) = YourAge will assign the value in the variable named YourAge to element 5 of the Age array.
You can create multidimensional arrays. Dim Phone(100, 4) will create an array with 101 elements and 5 subelements. For each subscript of the first part, you will be able to have 5 subelements (remember, the first element is 0). So, Phone(1,3) will return the fourth phone number for the second "record".
The ReDim keyword can be used to change the size of an array after it's created. There are a couple of caveats:
ReDim uses the same syntax as Dim. It does have one option, however. You can use the Preserve keyword to retain any preexisting contents of the array. (If you make the array smaller, of course, you'll lose anything in the elements that are removed.) To increase the size of an array named Count by 10, you'd use this code:
ReDim Count(Ubound(Count) + 10) Preserve
The Ubound function returns the number of the highest subscript in an array. So if the array was previously ReDimmed to 100, Ubound(Count) would return 100, and Ubound(Count) + 10 would equal 110, which is what the array would be ReDimmed to in this example.
VBScript also has an Lbound function, which returns the lowest subscript in an array. However, since all VBScript arrays begin with element 0, it's not of much use.
You can remove a dynamic array with the Erase statement. The following syntax demonstrates how to create and erase a dynamic array:
Dim ScratchVars()
ReDim ScratchVars(25)
Erase ScratchVars
You can use Erase with static arrays; however, it won't remove the arrayùit will only clear the contents of the elements it contains.
The IsArray function will return True if tested with a variable name, so IsArray(NameList) will return True if NameList is an array and False if it's a simple variable.
Comments are not executed. They are only for human eyes. By commenting your code, you make it easier to understand when you look at it later on. While it's easy to understand your code as you write it, it's amazingly easy to forget what's going on a month or two later when you revisit it. You can place comments in your code by using either Rem or [sp] (see Table 22.2).
Table 22.2 Comments
Keyword | Description |
Rem | Used at beginning of line to create comment ("Remark") |
' | Used anywhere in line, everything beyond is comment |
Rem is generally used when entering comments alone on a line, and [sp] is used when placing comments at the end of a line of code. (Rem is shorthand for remark.) Both are shown in the following example:
Rem This routine accepts a number and adds it to the running tally.
For C = 1 to Total 'Count through the list
The first line is a comment; it has no executable code. The second line consists of a line of code with a comment appended to the end.
Unlike Visual Basic, VBScript doesn't provide a way to use true Constants. If you need to define a constant, you'll have to use a variable as a pseudo-constant and be very careful to avoid changing it in code. There are, however, some built-in constants, such as True and False, and the Empty, Nothing, and Null keywords which exhibit constant-like behavior.
True and False contain the values -1 and 0, respectively. They're used when you're testing conditions returned by expressions and various functions. (Throughout this book, you'll see frequent reference to True and False as returned values.)
Empty is a special value used with variables. An Empty variable is one that has been created, but not yet assigned a value. With a numeric value, it is 0; with strings, it's "".
Null is another type of special value. It indicates that the variable is not valid. It is not equal to any value, therefore, it's not equal to 0 in a numeric variable nor is it equal to "" in a string. If any part of an expression is Null, the Null will propagate throughout the expression, and the result will be Null.
Nothing removes an object reference. If you create an object reference with
Set Handy=LongFormName.LongControlName
you'll be able to refer to LongFormName.LongControlName properties by using the Handy.Property format. To remove the Handy reference, use
Set Handy=Nothing
VBScript Assignment Operators are listed in Table 22.3. (The equals sign (=) and the Let keyword are fully discussed in Chapter 16, "VBScript Operators", in the "Equality" section.)
Table 22.3 Assignment Operators
Keyword | Description |
= | Assigns an expression to a variable |
Let | Obsolete statement used at start of assignment |
Set | Creates an Object Reference; useful for creating shortcuts to items in the Internet Explorer object hierarchy |
Set can be used to assign an object to a variable. The example in Listing 22.3 demonstrates one use of the Set keyword.
Listing 22.3 set.htmùExample of Set Operator
In Listing 22.3, a Form named LongFormName contains a Text control named LongControlName. To access the control's Value property, you can either use LongFormName.LongControlName.Value or use Set to assign a it to a variable. After the Set statement above creates the variable Handy, you can use it instead of the longer LongFormName.LongControlName, as demonstrated in the example.
YIt's important to note that you're not creating a new instance of the original object; you're simply assigning a type of alias to it. When you use the variable named Handy in the example, you're really using the actual control in LongFormName.LongControlName. When you run the example, you'll see It works! in the Text control, indicating that by setting Handy.Value, you're really working with the control.
Microsoft's Basic language implementations have always been noted for a rich set of string handling features. VBScript carries on with this tradition. Table 22.4 lists the string handling functions implemented in VBScript.
Table 22.4 String Handling Functions
Function | Description |
Asc, AscB, AscW | Returns the ASCII value of the first character in the string being evaluated |
Chr, ChrB, ChrW | Returns a one-character string representing the numeric value being evaluated |
Instr, InStrB, | Returns the position of a search string within a target string |
Len, LenB | Returns the length of a string |
LCase | Returns a lowercase representation of a string |
UCase | Returns an uppercase representation of a string |
Left, LeftB | Returns a specified number of leftmost characters in a string |
Right, RightB | Returns a specified number of rightmost characters in a string |
Mid, MidB | Returns a specified number of characters from a specified position in a string |
Space | Returns a string containing a specified series of space characters |
String | Returns a string containing a specified series of any specified character |
Ltrim | Returns a string which is a copy of the target string, with all leading spaces removed |
Rtrim | Returns a string which is a copy of the target string, with all trailing spaces removed |
Trim | Returns a string which is a copy of the target string, with all leading and trailing spaces removed |
CStr | Converts number to string |
StrComp | Performs a case-sensitive, or case-insensitive comparison on two strings |
Some string functions end with B or W. These functions are byte and wide equivalents for the corresponding functions without a suffixed letter. For instance, Len returns the length of a string in characters, but LenB returns the length in bytes. Asc returns a numeric value of a character, and AscW returns the numeric value of a Unicode character.
You'll probably be using the string handling functions extensively in your scripting work.
Asc and Chr are the inverse of each other. Asc returns the ASCII numeric value of a one-character string, and Chr returns a one-character string representing a numeric ASCII value. (ASCII means American Standard Code for Information Interchange.)
The syntax for Asc is NumericValue = Asc("A"), which would return 65. StringValue = Chr(65) would return "A".
To search a string for a sub-string, use the Instr function:
Source = "This is a test"
Search = "test"
Found = Instr(Source, Search)
Found will contain the position of Search within Source. So if Source contains "This is a test", and Search contains "test" Found will contain 11.
As this book goes to press, Microsoft documents a third optional parameter for Instr. If Found = Instr(Source, Search, 1) is used, the test will be case-insignificant. However, this option was not functional with the preliminary versions of software available for testing.
The Len function returns the length of a string. The syntax is this:
StringLength = Len(TestString)
LCase and UCase are used to respectively return a lowercase or uppercase representation of a target string. So, UCase("fubar") will return FUBAR.
Left and Right will return a specified number of the leftmost or rightmost characters of a string. For example, Left(Source, 10) will return the first 10 characters of Source.
If you're a Visual Basic programmer, you know that Mid is unique in that it can be used as a function or a statement. VBScript, however, only provides the Function implementation of Mid.
Mid returns a specified numbers of characters of a string, just like Left and Right; however, unlike those functions, it accepts a starting position. So, Fragment = Mid(Source, 5, 2) will return the two characters starting with the fifth character of Source.
Space returns a string containing the specified number of space characters. Space(10) returns a string consisting of ten spaces.
String is similar to Space, but it allows you to specify which character to return. You supply a string or a literal, and a number. So, String(25, "*") will return a string consisting of 25 "*" characters. You can alternatively supply an ASCII number instead of a string for the second argument. In that case, String(10, 32) will return ten spaces. (32 is the ASCII code for the space character.)
Ltrim, Rtrim, and Trim remove leading, trailing, or leading and trailing spaces from a string. Ltrim(User) will return the contents of User, with any leading spaces removed. Rtrim works the same way for trailing spaces, and Trim removes leading and trailing spaces.
CStr returns a string representation of a number. CStr(5) will return a string containing "5". CStr is aware of international conversion issues, such as different style decimal separators. Additionally, it will convert Boolean (True/False), Date, and Error values to strings.
StrComp is used to compare one string against another. If you know that both strings being compared are of the same case, you can simply use an equal sign to compare. Thus, if String1 = "Cantaloupe" and String2 = "CANTALOUPE", testing If String1 = String2 will fail. StrComp can be used to perform case-significant or case-insignificant tests, by using the syntax: Test = StrComp(String1, String2, CompareMode). If CompareMode is 0 (or, if CompareMode is absent) the test will be case-significant, just like an equal sign test. But if CompareMode is 1, the test will be case-insignificant.
Table 22.5 presents the control flow statements and their descriptions.
Table 22.5 Control Flow Statements
Statement | Description |
Do...Loop | Executes code block while or until a test condition is met |
While...Wend | Executes code block while test condition is met |
For...Next | Executes code block a specified number of times |
If...Then...Else | Executes code block(s) depending on results of test |
Select Case | Tests for multiple conditions, executes corresponding Space blocks of code |
Table 22.6 shows the various variant subtypes.
Table 22.6 Variant Subtypes
Subtype | Description |
IsArray | Tests if subtype of variable is Array |
IsDate | Tests if variable or expression returns a Date |
IsEmpty | Tests if variable is uninitialized |
IsNull | Tests if variable is initialized, but does not contain data |
IsNumeric | Tests if variable or expression returns a valid number |
IsObject | Tests if variable refers an OLE automation object |
VarType | Returns a String containing the subtype of a specified variable |
VBScript does not have true variable typing; all variables are of the Variant type. However, Variants can contain any variable type as a subtype. Whenever a type (such as String, Date, and so on) is mentioned, it should be understood to refer to a Variant subtype (see Table 22.6).
See "The Variant's Data Sub-Types," for a full discussion of data types and programming issues. [Chapter 15, "VBScript Data Types and Variables"]
See "What Is an Object," for more information about object usage. [Chapter 11, "Designing VBScript Applications"]
The math functions provide a variety of trigonometric, logarithmic, and other mathematical capabilities. Table 22.7 lists these functions.
Table 22.7 Math Functions
Function | Description |
Atn | Returns the arctangent of a number or expression |
Cos | Returns the cosine of a number or expression |
Sin | Returns the sine of a number or expression |
Tan | Returns the tangent of a number or expression |
Exp | Returns e raised to a power from a number or expression |
Log | Returns the natural (base e) logarithm of a number or expression |
Sqr | Returns the square root of a number or expression |
Randomize | Seeds the random number generator |
Rnd | Returns a random number |
The Atn, Cos, Sin, and Tan trigonometric functions all use the same simple syntax (keyword(number)) to return their respective value:
Atn(35)
The Exp and Log logarithmic functions also use that syntax to return their results, as does the Sqr square root function.
Randomize and Rnd are used for seeding the random number generator and for generating a random number. Using Randomize by itself causes the random number generator to be seeded with the current value in the system timer. You can also place a number or numeric argument after Randomize and use that value as a seed, such as Randomize 7365.
To retrieve a random number, use this syntax:
RandomNumber = Rnd
The variable (in this case, RandomNumber) will contain a random number within the range of 0û1. The Rnd function will accept a number as an optional argument. If you supply one, the following rules are used:
Random Number Trivia
The numbers returned by the random number generator (a built-in part of VBScript) are not truly random. Technically, they are referred to as pseudo-random numbers. Each time the random number generator is started, it produces a sequence of random numbers. By using Rnd with a negative argument one time before calling Randomize with a seed, you can produce identical "runs" of pseudo-random numbers. (Remember to use the same seed value for Randomize each time too when doing this.)
Even though the number returned by Rnd is limited to the range of 0û1, you can convert this to other ranges. By using the formula Int((HighRangeû LowRange + 1) * Rnd + LowRange), you can produce random numbers in any range. (Assign your lowest and highest desired numbers to LowRange and HighRange before calling this formula, and it will return a result in the desired range.)
The following expression returns a random number between 10 and 20:
Int((20 - 11) * Rnd + 10)
VBScript has a wealth of Date and Time functions. Table 22.8 lists those functions.
Table 22.8 Date and Time Functions
Function | Description |
Now | Returns the current Date and Time |
CDate | Returns a Date type representation of a number or expression |
Date | Returns the current Date |
DateSerial | Returns a Date type variable (containing the date) representing the Date of a specified Year, Month, and Day |
DateValue | Returns a Date type variable(containing the date) from a string variable or expression containing text representing a date |
Day | Returns the day of month for a specified date |
Month | Returns the number of the month for a specified date |
Weekday | Returns a number representing the day of the week for a specified date (1 = Sunday, 2 = Monday, and so on) |
Year | Returns the year part of a specified date |
Time | Returns the current Time |
TimeSerial | Returns a Date type variable (containing the time) when provided a specfied time in parameters containing the hour, minute, and second |
TimeValue | Returns a Date type variable (containing the time) from a string variable or expression containing text representing a time |
Hour | Returns a number representing the Hour of a specified time |
Minute | Returns a number representing the Minute of a specified time |
Second | Returns a number representing the Second of a specified time |
Date returns the current date as a string in the form of 1/1/97. Time likewise returns the current time, in the form of a string like 12:00:00 PM. Now returns both date and time in one string, such as 1/1/97 12:00:00 PM. All three of these functions are used without arguments. Like all functions, you can assign them anywhere it's legal to accept a value, such as a variable or the Value property of a Text control.
DateSerial returns a Date sub-typed variant when passed three arguments (for Year, Month, and Day). DateSerial(1997, 1, 1) will return a variable containing the date for 1/1/97. You can do simple date math by adding (or subtracting) a value to any of these three parameters. So, DateSerial(1997, 1û5, 3) will return 8/3/96.
DateValue also returns a Date sub-typed variant, but it accepts a single string, using many common date formats, such as 4/16/1975 and 11/16/76. It can also recognize text representations of dates, such as October 23, 1949 (common abbreviations such as Oct are also accepted).
TimeSerial is identical in use to DateSerial, but using Hour, Minute, and Second in place of Year, Month, and Date. It returns a variable containing the time represented by the combined parameters.
TimeValue is likewise identical in form to DateValue but accepting common time formats (such as 8:00PM or 20:00) in its single parameter. It returns a variable containing the time as interpreted from the string supplied in the parameter.
Year, Month, and Day return their respective values when passed a Date. You can use common forms of date, so Year("Dec 25, 1997") will return 1997, for instance.
Hour, Minute, and Second are the time counterparts to the Year, Month, and Day functions, and use the same syntax. They return their respective values when passed any valid time in their parameter.
In VBScript, all variables are of Variant type. A variant can hold any type of data. VBScript assigns a subtype to a variant depending on content, context, and by using conversion functions (listed in Table 22.9). In most cases, conversion is automatic and transparent. When you want to override the settings created by the content of a variable, or the context in which it is assigned a value, you can use the conversion functions.
Table 22.9 Conversion Functions
Function | Description |
Abs | Returns the Absolute value of a number or expression |
Asc | (Described in String Functions) |
Chr | (Described in String Functions) |
CBool | Evaluates an expression and returns either True or False (if non-zero, True; otherwise, False) |
CByte | Returns a Byte type representation of a number or expression |
CDate | (Described in Date and Time Functions) |
CDbl | Returns a Double precision type representation of a number or expression |
CInt | Returns an Integer type representation of a number or expression |
CLng | Returns a Long type representation of a number or expression |
CSng | Returns a Single precision type representation of a number or expression |
CStr | (Described in String Functions) |
DateSerial | (Described in Date and Time Functions) |
DateValue | (Described in Date and Time Functions) |
Fix | Same as Int for positive values, but returns next lower whole negative number for negative values |
Hex | Returns a String containing a Hexadecimal (base 16) representation of a specified number or expression (the opposite can be accomplished by prefixing a hex number with &H; for instance, &HFF equals 255) |
Int | Returns next lower whole number value for positive values, next higher whole negative number for negative values |
Oct | Returns a String containing an Octal (base 8) representation of a specified number or expression (the opposite can be accomplished by prefixing a hex number with &O (that is the letter O, not a zero); in other words, &O77 equals 63 decimal) |
Sgn | Returns the sign of a number or expression; 1 if positive value, -1 if negative value |
TimeSerial | (Described in Date and Time Functions) |
TimeValue | (Described in Date and Time Functions) |
Int, CInt, and Fix are related functions that return integers. For positive numbers, Int and Fix round down to the next lowest integer, and CInt rounds up. For negative numbers, CInt and Fix round up toward zero, and Int rounds down to the next highest negative number. (So, CInt(-1.6) returns -2, but Fix(-1.6) returns -1, while Int(-1.4) returns -2, and Fix(-1.4) returns -1.)
Abs returns the Absolute Value (the number without its sign) of a variable. Abs(1.23) and Abs(-1.23) will both return 1.23.
CBool, CByte, CDbl, CLng, and CSng convert a number to their respective sub-types as described in Table 22.9. They all use the Result = Keyword(Value) syntax. So, in the expression Answer = CBool("True"), Answer will contain -1.
Hex and Oct return strings containing Hexadecimal and Octal equivalents for decimal arguments. Hex(255) returns FF, and Oct(255) returns 377 (&hff and &o377 both return 255, as described in Table 22.9).
The Sgn function accepts a single argument and returns either 1 or -1 depending on the sign of the value passed. Sgn(25) will return 1, and Sgn(-25) will return -1.
The two built-in modal dialogsùInputBox and MsgBox (see Table 22.10)ùare useful for times when you need to either notify the user of something out of the ordinary or to obtain a short bit of information via keyboard input.
Modal means that the rest of the application is suspended while the dialog is visible.
Table 22.10 Input/Output
Keyword | Description |
MsgBox | Displays short message and optionally returns a value indicating which of a series of buttons was clicked |
InputBox | Accepts text entry and returns it as a String value |
MsgBox creates a MessageBox and takes two forms: it can be used as a statement or as a function. In its simplest form, it takes a single string argument and waits until OK is clicked. The following statement:
MsgBox "Click me!"
will result in a MessageBox with Visual Basic in the title bar, Click me! in the center, and a single button labeled OK. The underlying script that invokes the MessageBox will pause until the user clicks OK.
MsgBox can also be used as a function. When placed on the right side of an equal sign, it will return a value to the variable on the left side. When used as a function, the parameters have to be enclosed in parentheses, as is the case with all function calls.
Optional parameters are available for Buttons, Title, HelpFile, and HelpContext. (For information on creating your own Windows help files, see Que's Designing Windows Help Systems.)
This is the MsgBox syntax:
MsgBox(Prompt, Buttons, Title, Helpfile, HelpContext)
This is a typical invocation of the MsgBox function:
Value = MsgBox("Click me!", 4, "A Test", "C:\MyDir\MyApp.hlp", 123)
Figure 22.1 shows the MsgBox the above expression creates.
Whatever you enter for the Title parameter will appear on top of the MessageBox when it's displayed. It's similar to a form's Caption property in Visual Basic.
Using the Buttons parameter can be a bit tricky. The number you enter determines how many buttons are displayed, how they're labeled, which (if any) icon is displayed on the MessageBox, the default button, and the level of modality. The following tables (22.11 through 22.14) will help you make sense of it.
FIG. 22.1
A MsgBox.
Table 22.11 MessageBox Button Options: Buttons
Value | Button(s) |
0 | OK |
1 | OK, Cancel |
2 | Abort, Retry, Ignore |
3 | Yes, No, Cancel |
4 | Yes, No |
5 | Retry, Cancel |
If the value of the Button parameter is 0, or if it's missing, only the OK button will be displayed. Otherwise, the five other options are available.
Table 22.12 MessageBox Button Options: Icons
Value | Icon |
16 | Critical Message (red circle/"X") |
32 | Warning Query (Question Mark) |
48 | Warning Message (Exclamation Mark) |
64 | Information Message (Small "i") |
When the Button value is 0, or is missing, no icon will be displayed.
Table 22.13 MessageBox Button Options: Defaults
Value | Default Button |
0 | First |
256 | Second |
512 | Third |
768 | Fourth |
When only one button is displayed, it will be the default.
Table 22.14 MessageBox Button Options: Modality
Value | Modality |
0 | Application (Internet Explorer is suspended while MessageBox is displayed) |
4096 | System (All applications are suspended while MessageBox is displayed) |
System modality is essentially imaginary in 32-bit Windows. It's accepted as part of the API but has no modal effect. Other programs can continue to be accessed, even thought the system modal flag is set. It will, however, be an "always on top" window, which means that even though you can continue to interact with other applications, the system-modal MessageBox will always float on top of any other windows on your screen.
You may be wondering how to combine this mess of information spread over several tables into one variable. Actually, it's quite simpleùyou just add them all together! Take one selection from each table, add them together, and you'll have all the effects you specified. So, Value = MsgBox("Click me!", 2 + 32 + 256 + 4096) will result in a system-modal MessageBox, with three buttons (Abort, Retry, Ignore), the second (Retry) button as the default, and a question-mark icon.
Once you're able to create the type of MessageBox you need, you're most of the way home. The only remaining issue is how to determine which button was clicked after the MsgBox function executes. The answer is always returned by the function, according to Table 22.15.
Table 22.15 MsgBox Return Values
Value | Button |
1 | OK |
2 | Cancel |
3 | Abort |
4 | Retry |
5 | Ignore |
6 | Yes |
7 | No |
If the user presses Enter, the effect will be the same as if the default button was clicked. And pressing Esc will have the same result as clicking Cancel (if present).
The InputBox function displays an application-modal dialog and contains a single TextBox that can accept keyboard entry. The syntax is generally similar to MsgBox, with a few differences. Unlike MsgBox, InputBox has no confusing proliferation of numeric options for buttons, icons, and modality. InputBox is pretty straightforward in that regard. The user sees one TextBox, two buttons (OK and Cancel, with OK always the default) and optionally a title and prompt. When OK is clicked, or Enter is pressed, any text contained in the TextBox is returned by the InputBox. When Cancel is clicked, or Esc is pressed, InputBox returns an empty string ("").
In addition to the absence of a Buttons parameter, the InputBox function has Default, Xpos, and Ypos parameters. The syntax for InputBox is this:
InputBox(Prompt, Title, Default, Xpos, Ypos, Helpfile, HelpContext)
You must have at least the Prompt parameter. All others are optional. If you skip a parameter, you need to include a comma in its place. Also, if you use Xpos, you must use Ypos, and vice versa. Similarly, HelpFile, and HelpContext must also be used with each other.
If you want the InputBox to contain any preexisting text when it appears, place the text in the Default parameter. If the Default parameter is absent, the TextBox will be empty when the user first sees it.
Xpos and Ypos determine where the InputBox will appear on the user's screen. You can either enter a value in Twips for each of them, or, leave them empty. Xpos determines the distance from the left edge of the screen, and Ypos determines placement relative to the top of the screen. If you do not provide Xpos and Ypos parameters, the InputBox will appear horizontally centered and about 1/3 of the way down from the top of the screen.
A Twip is a typesetting unit of measurement, equal to 1/1440 of an inch.
The following expression creates an input box with a title of Flavor Entry, and a prompt asking Which flavor? If the user just clicks Ok without entering anything, the default value of Vanilla will be returned to the Flavor variable.
Flavor = InputBox("Which flavor?", "Flavor Entry", "Vanilla")
Error handling in VBScript is a simplified version of that which VB provides. Most of the On Error and Resume options are unimplemented. On Error Resume Next, which forces the code to continue execution when an error occurs, and On Error Goto 0, which turns off error handling, are the only error handling statements. The Error Object contains several properties which are set when an error occurs; testing it after an operation that is suspected of causing an error is your only available means of error trapping.
Functions and values are useless without a means of assigning, testing, and otherwise accessing them. VBScript implements a rich set of Operators, which provide the ability to assign, compare, combine, and perform math on variables and expressions.
VBScript Operators, (+ - * /\ > < = etc.) are covered in Chapter 16, "VBScript Operators."
Traditional object management is essentially nonexistent in VBScript. The CreateObject and IsObject keywords are supported, but you cannot create objects when your scripts are used in Internet Explorer, due to security considerations. If you are writing your own script object server (a non-trivial task, unrelated to the subject of Web page automation), you can use these features.
You can include objects written in other languages, such as Visual Basic, if they are properly registered. The <OBJECT> tag provides the means for this.
VBScript's implementation of the Basic language is very powerful. Even though it's a subset of the full VB language, its features merit attention and study. The following resources will prove invaluable in helping you to learn the language.
| Previous Chapter | Next Chapter |
| Search | Table of Contents | Book Home Page | Buy This Book |
| Que Home Page | Digital Bookshelf | Disclaimer |
To order books from QUE, call us at 800-716-0044 or 317-361-5400.
For comments or technical support for our books and software, select Talk to Us.
© 1996, QUE Corporation, an imprint of Macmillan Publishing USA, a Simon and Schuster Company.